import React, { useState, useEffect, useRef } from 'react';
import { Plus, Download, Upload, Trash2, Settings, RefreshCw, Database, Filter, Shield } from 'lucide-react';
import { useApp } from '../../../contexts/AppContext';
import { TabBar } from '../../../components/TabBar';
import { AddressBar } from '../../../components/AddressBar';
import { BrowserTab } from './BrowserTab';
import { TabManager } from '../utils/TabManager';
import { SessionManager } from '../utils/SessionPersistence';
import { BatchOperationsManager } from '../utils/BatchOperations';
import { GlobalCookieInterceptor } from '../utils/CookieInterceptor';
import { CookieInterceptorPanel } from './CookieInterceptorPanel';

const tabManager = new TabManager();
const sessionManager = SessionManager.getInstance();
const batchOpsManager = BatchOperationsManager.getInstance();

export function IsolatedBrowserLayout() {
  const { state, dispatch } = useApp();
  const [newTabUrl, setNewTabUrl] = useState('https://www.douyin.com');
  const [selectedAccount, setSelectedAccount] = useState<string>('');
  const [showBatchMenu, setShowBatchMenu] = useState(false);
  const [showSessionMenu, setShowSessionMenu] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [sessionStats, setSessionStats] = useState({ tabs: 0, cookies: 0 });
  const [showInterceptorPanel, setShowInterceptorPanel] = useState(false);
  const batchMenuRef = useRef<HTMLDivElement>(null);
  const sessionMenuRef = useRef<HTMLDivElement>(null);
  const iframeRefs = useRef<Record<string, HTMLIFrameElement>>({});

  // 组件挂载时恢复会话
  useEffect(() => {
    const initializeSession = async () => {
      setIsLoading(true);
      
      try {
        // 检查是否有待恢复的会话
        const restoredSession = await sessionManager.restoreSessionIfNeeded();
        
        if (restoredSession) {
          // 恢复标签页
          restoredSession.tabs.forEach(tab => {
            dispatch({ type: 'ADD_TAB', payload: tab });
          });
          
          // 设置活跃标签页
          if (restoredSession.activeTabId) {
            dispatch({ type: 'SWITCH_TAB', payload: restoredSession.activeTabId });
          }
          
          console.log('会话恢复完成', restoredSession);
        }
        
        // 更新会话统计
        updateSessionStats();
        
        // 启动自动保存
        sessionManager.getPersistence().startAutoSave(
          () => ({ tabs: state.tabs, activeTabId: state.activeTabId }),
          30000
        );
        
      } catch (error) {
        console.error('初始化会话失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    initializeSession();
  }, []);

  // 更新会话统计
  const updateSessionStats = () => {
    const stats = batchOpsManager.getBatchOperations().getBatchStatistics(state.tabs);
    setSessionStats({
      tabs: stats.totalTabs,
      cookies: stats.totalCookies
    });
  };

  // 监听标签页变化，更新统计
  useEffect(() => {
    updateSessionStats();
    
    // 自动保存会话状态
    if (state.tabs.length > 0) {
      sessionManager.getPersistence().autoSaveSession(state.tabs, state.activeTabId);
    }
  }, [state.tabs, state.activeTabId]);

  // 处理点击外部关闭菜单
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (batchMenuRef.current && !batchMenuRef.current.contains(event.target as Node)) {
        setShowBatchMenu(false);
      }
      if (sessionMenuRef.current && !sessionMenuRef.current.contains(event.target as Node)) {
        setShowSessionMenu(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // 获取当前活跃的标签页
  const activeTab = state.tabs.find(tab => tab.isActive);

  // 批量操作功能
  const handleBatchExport = async (format: 'json' | 'csv' | 'txt', platform?: string) => {
    try {
      const result = await batchOpsManager.getBatchOperations().exportAllCookies(state.tabs, {
        includeCookies: true,
        includeLocalStorage: false,
        includeSessionInfo: true,
        format,
        filterByPlatform: platform
      });
      
      batchOpsManager.getBatchOperations().downloadExportFile(result);
      setShowBatchMenu(false);
      
      alert(`导出成功！共导出 ${result.exportedTabs} 个标签页，${result.totalCookies} 个Cookie。`);
    } catch (error) {
      console.error('批量导出失败:', error);
      alert('导出失败，请查看控制台获取详细信息。');
    }
  };

  const handleBatchClearCookies = () => {
    if (confirm('确定要清除所有标签页的Cookie吗？此操作不可撤销。')) {
      batchOpsManager.quickClearAllCookies(state.tabs);
      setShowBatchMenu(false);
    }
  };

  const handleShowStatistics = () => {
    batchOpsManager.showStatistics(state.tabs);
    setShowBatchMenu(false);
  };

  // 会话管理功能
  const handleSaveSession = () => {
    sessionManager.getPersistence().forceSaveSession(state.tabs, state.activeTabId);
    setShowSessionMenu(false);
    alert('会话状态已保存！');
  };

  const handleClearSession = () => {
    if (confirm('确定要清除所有保存的会话数据吗？重启后将无法恢复当前状态。')) {
      sessionManager.getPersistence().clearSession();
      setShowSessionMenu(false);
      alert('会话数据已清除！');
    }
  };

  const handleExportSession = () => {
    const sessionData = sessionManager.getPersistence().exportSession();
    if (sessionData) {
      const blob = new Blob([sessionData], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `session_backup_${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
      a.click();
      URL.revokeObjectURL(url);
      setShowSessionMenu(false);
      alert('会话备份已导出！');
    }
  };

  const handleImportSession = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const sessionData = e.target?.result as string;
        const success = sessionManager.getPersistence().importSession(sessionData);
        
        if (success) {
          alert('会话备份导入成功！重启应用后即可恢复。');
        } else {
          alert('会话备份导入失败，请检查文件格式。');
        }
      } catch (error) {
        console.error('导入会话失败:', error);
        alert('导入失败，请查看控制台获取详细信息。');
      }
      
      setShowSessionMenu(false);
      event.target.value = ''; // 重置文件输入
    };
    reader.readAsText(file);
  };

  // 创建新标签页
  const handleCreateTab = () => {
    const tabId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    const newTab = {
      id: tabId,
      title: '新建标签页',
      url: newTabUrl,
      accountId: selectedAccount || undefined,
      isActive: true,
      platform: selectedAccount ? 
        state.accounts.find(acc => acc.id === selectedAccount)?.platform : undefined
    };

    // 创建标签页会话
    const account = selectedAccount ? state.accounts.find(acc => acc.id === selectedAccount) : undefined;
    tabManager.createSession(tabId, {
      accountId: selectedAccount,
      platform: account?.platform,
      initialUrl: newTabUrl
    });

    dispatch({ 
      type: 'ADD_TAB', 
      payload: newTab 
    });

    // 关闭其他标签页的活跃状态
    state.tabs.forEach(tab => {
      if (tab.id !== tabId) {
        dispatch({ 
          type: 'SWITCH_TAB', 
          payload: tabId 
        });
      }
    });
  };

  // 关闭标签页
  const handleCloseTab = (tabId: string) => {
    // 销毁标签页会话
    tabManager.destroySession(tabId);
    
    dispatch({ 
      type: 'CLOSE_TAB', 
      payload: tabId 
    });
  };

  // 切换标签页
  const handleSwitchTab = (tabId: string) => {
    dispatch({ 
      type: 'SWITCH_TAB', 
      payload: tabId 
    });
    
    // 更新会话活跃时间
    tabManager.updateSessionActivity(tabId);
  };

  // 导航到新URL
  const handleNavigate = (url: string) => {
    if (activeTab) {
      dispatch({ 
        type: 'UPDATE_TAB_URL', 
        payload: { id: activeTab.id, url } 
      });
    }
  };

  // 刷新页面
  const handleRefresh = () => {
    if (activeTab && iframeRefs.current[activeTab.id]) {
      const iframe = iframeRefs.current[activeTab.id];
      if (iframe) {
        iframe.src = iframe.src;
      }
    }
  };

  // 主页
  const handleHome = () => {
    handleNavigate('https://www.douyin.com');
  };

  // 后退和前进（需要iframe引用）
  const iframeRefs = React.useRef<Record<string, HTMLIFrameElement>>({});

  const handleGoBack = () => {
    if (activeTab && iframeRefs.current[activeTab.id]) {
      const iframe = iframeRefs.current[activeTab.id];
      if (iframe && iframe.contentWindow) {
        iframe.contentWindow.history.back();
      }
    }
  };

  const handleGoForward = () => {
    if (activeTab && iframeRefs.current[activeTab.id]) {
      const iframe = iframeRefs.current[activeTab.id];
      if (iframe && iframe.contentWindow) {
        iframe.contentWindow.history.forward();
      }
    }
  };

  // 检查是否可以前进后退
  const canGoBack = activeTab ? true : false;
  const canGoForward = activeTab ? true : false;

  return (
    <div className="flex flex-col w-full h-screen bg-white">
      {/* 标签页栏 */}
      <div className="flex-shrink-0">
        <TabBar 
          onNewTab={handleCreateTab}
        />
      </div>

      {/* 地址栏和控件 */}
      <div className="flex-shrink-0">
        <AddressBar
          url={activeTab?.url || ''}
          onNavigate={handleNavigate}
          onRefresh={handleRefresh}
          onHome={handleHome}
          canGoBack={canGoBack}
          canGoForward={canGoForward}
          onGoBack={handleGoBack}
          onGoForward={handleGoForward}
        />
      </div>

      {/* 工具栏区域 */}
      <div className="flex items-center justify-between p-3 bg-gray-50 border-b">
        {/* 左侧：创建标签页控件 */}
        <div className="flex items-center space-x-4">
          <button
            onClick={handleCreateTab}
            className="flex items-center px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            <Plus size={16} className="mr-2" />
            新建标签页
          </button>

          <div className="flex items-center space-x-2">
            <label className="text-sm text-gray-600">URL:</label>
            <input
              type="text"
              value={newTabUrl}
              onChange={(e) => setNewTabUrl(e.target.value)}
              className="px-2 py-1 border border-gray-300 rounded text-sm w-64"
              placeholder="https://www.douyin.com"
            />
          </div>

          <div className="flex items-center space-x-2">
            <label className="text-sm text-gray-600">账号:</label>
            <select
              value={selectedAccount}
              onChange={(e) => setSelectedAccount(e.target.value)}
              className="px-2 py-1 border border-gray-300 rounded text-sm"
            >
              <option value="">无账号</option>
              {state.accounts.map(account => (
                <option key={account.id} value={account.id}>
                  {account.username} ({account.platform})
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* 右侧：批量操作和会话管理按钮 */}
        <div className="flex items-center space-x-2">
          {/* Cookie拦截器按钮 */}
          <button
            onClick={() => setShowInterceptorPanel(true)}
            className="flex items-center px-3 py-2 bg-orange-500 text-white rounded hover:bg-orange-600"
            title="Cookie拦截器"
          >
            <Shield size={16} className="mr-2" />
            拦截器
          </button>

          {/* 批量操作按钮 */}
          <div className="relative" ref={batchMenuRef}>
            <button
              onClick={() => setShowBatchMenu(!showBatchMenu)}
              className="flex items-center px-3 py-2 bg-green-500 text-white rounded hover:bg-green-600"
              title="批量操作"
            >
              <Download size={16} className="mr-2" />
              批量操作
            </button>

            {showBatchMenu && (
              <div className="absolute right-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded shadow-lg z-20">
                <div className="p-2 border-b border-gray-200">
                  <span className="text-sm font-medium text-gray-700">批量导出</span>
                </div>
                
                <button
                  onClick={() => handleBatchExport('json')}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
                >
                  <Download size={14} className="mr-2" />
                  导出所有JSON
                </button>
                
                <button
                  onClick={() => handleBatchExport('csv')}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
                >
                  <Download size={14} className="mr-2" />
                  导出所有CSV
                </button>
                
                <div className="p-2 border-b border-gray-200 mt-1">
                  <span className="text-sm font-medium text-gray-700">平台导出</span>
                </div>
                
                {['抖音', '快手', '小红书', '微博', 'B站'].map(platform => (
                  <button
                    key={platform}
                    onClick={() => handleBatchExport('json', platform)}
                    className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
                  >
                    <Filter size={14} className="mr-2" />
                    {platform}平台
                  </button>
                ))}
                
                <div className="p-2 border-b border-gray-200 mt-1">
                  <span className="text-sm font-medium text-gray-700">管理</span>
                </div>
                
                <button
                  onClick={handleBatchClearCookies}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100 text-red-600"
                >
                  <Trash2 size={14} className="mr-2" />
                  清除所有Cookie
                </button>
                
                <button
                  onClick={handleShowStatistics}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
                >
                  <Database size={14} className="mr-2" />
                  查看统计
                </button>
              </div>
            )}
          </div>

          {/* 会话管理按钮 */}
          <div className="relative" ref={sessionMenuRef}>
            <button
              onClick={() => setShowSessionMenu(!showSessionMenu)}
              className="flex items-center px-3 py-2 bg-purple-500 text-white rounded hover:bg-purple-600"
              title="会话管理"
            >
              <Settings size={16} className="mr-2" />
              会话管理
            </button>

            {showSessionMenu && (
              <div className="absolute right-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded shadow-lg z-20">
                <div className="p-2 border-b border-gray-200">
                  <span className="text-sm font-medium text-gray-700">会话操作</span>
                </div>
                
                <button
                  onClick={handleSaveSession}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
                >
                  <Download size={14} className="mr-2" />
                  立即保存
                </button>
                
                <button
                  onClick={handleExportSession}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
                >
                  <Upload size={14} className="mr-2" />
                  导出备份
                </button>
                
                <label className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100 cursor-pointer">
                  <Upload size={14} className="mr-2" />
                  导入备份
                  <input
                    type="file"
                    accept=".json"
                    onChange={handleImportSession}
                    className="hidden"
                  />
                </label>
                
                <button
                  onClick={handleClearSession}
                  className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100 text-red-600"
                >
                  <Trash2 size={14} className="mr-2" />
                  清除会话
                </button>
              </div>
            )}
          </div>

          {/* 刷新按钮 */}
          <button
            onClick={handleRefresh}
            className="flex items-center px-3 py-2 bg-gray-500 text-white rounded hover:bg-gray-600"
            title="刷新"
          >
            <RefreshCw size={16} />
          </button>
        </div>
      </div>

      {/* 标签页内容区域 */}
      <div className="flex-1 relative">
        {state.tabs.length === 0 ? (
          <div className="flex items-center justify-center h-full bg-gray-100">
            <div className="text-center">
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                欢迎使用多账号浏览器
              </h3>
              <p className="text-gray-600 mb-4">
                点击上方按钮创建您的第一个隔离标签页
              </p>
              <button
                onClick={handleCreateTab}
                className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
              >
                创建标签页
              </button>
            </div>
          </div>
        ) : (
          state.tabs.map(tab => (
            <BrowserTab
              key={tab.id}
              tabId={tab.id}
              url={tab.url}
              title={tab.title}
              isActive={tab.isActive}
              accountId={tab.accountId}
              onClose={handleCloseTab}
              onSwitch={handleSwitchTab}
              onUrlChange={(tabId, newUrl) => {
                dispatch({
                  type: 'UPDATE_TAB_URL',
                  payload: { id: tabId, url: newUrl }
                });
              }}
              ref={(el) => {
                if (el) {
                  iframeRefs.current[tab.id] = el;
                } else {
                  delete iframeRefs.current[tab.id];
                }
              }}
            />
          ))
        )}
      </div>

      {/* 底部状态栏 */}
      <div className="flex-shrink-0 bg-gray-100 border-t border-gray-200 px-4 py-2 text-xs text-gray-600">
        <div className="flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <span>
              活跃标签页: {state.tabs.filter(tab => tab.isActive).length} / {sessionStats.tabs}
            </span>
            <span>
              Cookie总数: {sessionStats.cookies} 个
            </span>
            <span className="flex items-center">
              <span className="w-2 h-2 bg-green-500 rounded-full mr-1"></span>
              会话隔离: 已启用
            </span>
            <span className="flex items-center">
              <span className="w-2 h-2 bg-blue-500 rounded-full mr-1"></span>
              自动保存: 已启用
            </span>
          </div>
          
          <div className="flex items-center space-x-2">
            {isLoading && (
              <span className="flex items-center text-blue-500">
                <RefreshCw size={12} className="animate-spin mr-1" />
                正在加载会话...
              </span>
            )}
            <span>
              最后保存: {new Date().toLocaleTimeString()}
            </span>
          </div>
        </div>
      </div>

      {/* Cookie拦截器控制面板 */}
      <CookieInterceptorPanel
        tabs={state.tabs}
        isOpen={showInterceptorPanel}
        onClose={() => setShowInterceptorPanel(false)}
      />
    </div>
  );
}